package com.prim.update.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * ================================================
 * 作    者：linksus
 * 版    本：1.0
 * 创建日期：3/5 0005
 * 描    述：
 * 修订历史：
 * ================================================
 */
public class Utils {

    @SuppressLint("StaticFieldLeak")
    private static Application sApplication;

    /**
     * Init utils.
     * <p>Init it in the class of Application.</p>
     *
     * @param context
     *         context
     */
    public static void init(@NonNull final Context context) {
        Utils.sApplication = ((Application) context.getApplicationContext());
    }

    /**
     * Return the context of Application object.
     *
     * @return the context of Application object
     */
    public static Application getApp() {
        if (sApplication != null) return sApplication;
        throw new NullPointerException("u should init first");
    }

    /** 检查是否为空 */
    public static <T> T checkNotNull(T object, String message) {
        if (object == null) {
            throw new NullPointerException(message);
        }
        return object;
    }

    /** 拼接URL get */
    public static String createUrlFromParams(String url, Map<String, String> params) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(url);
            if (url.indexOf('&') > 0 || url.indexOf('?') > 0) sb.append("&");
            else sb.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                String encode = URLEncoder.encode(value, "utf-8");
                sb.append(key).append("=").append(encode);
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    public static boolean checkWifi(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        }
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI;
    }

    public static boolean checkNetwork(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        }
        NetworkInfo info = connectivity.getActiveNetworkInfo();
        return info != null && info.isConnected();
    }

    private static final int DAY = 24 * 60 * 60;

    /**
     * 根据时间戳获取描述性时间，如3分钟前，1天前
     *
     * @param timestamp
     *         时间戳 单位为毫秒
     *
     * @return 时间字符串
     */
    public static boolean getUpdateTime(String timestamp, int period) {
        String newTimesTamp = timestamp;
        if (timestamp.length() == 10) {
            newTimesTamp = timestamp + "000";
        }
        // 获取系统当前的时间（毫秒）
        long currentTime = System.currentTimeMillis();
        // 传入的时间和系统的时间差（秒）
        long timeGap = (currentTime - Long.valueOf(newTimesTamp)) / 1000;
        boolean timeStr = false;
        if (timeGap >= period * DAY) {
            timeStr = true;
        } else {
            timeStr = false;
        }
        return timeStr;
    }
}
